﻿#include "appkey.h"
#include "qmutex.h"
#include "qfile.h"
#include "qtimer.h"
#include "qdatetime.h"
#include "qapplication.h"
#include "qmessagebox.h"
#pragma execution_character_set("utf-8")
AppKey *AppKey::self = NULL;
AppKey *AppKey::Instance()
{
    if (!self) {
        QMutex mutex;
        QMutexLocker locker(&mutex);
        if (!self) {
            self = new AppKey;
        }
    }

    return self;
}

AppKey::AppKey(QObject *parent) : QObject(parent)
{
    keyData = "";
    keyUseDate = false;
    keyDate = "2017-01-01";
    keyUseRun = false;
    keyRun = 1;
    keyUseCount = false;
    keyCount = 10;

    timer = new QTimer(this);
    timer->setInterval(1000);
    connect(timer, SIGNAL(timeout()), this, SLOT(checkTime()));
    startTime = QDateTime::currentDateTime();
}

QString AppKey::ReadRegedit()
{
    QCoreApplication::setOrganizationName(QString("Bruce"));
    QCoreApplication::setApplicationName(QString("Test"));
    QSettings settings(QSettings::NativeFormat, QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName());
    QString str = settings.value("key").toString();
    return str;
}
QString AppKey::WriteRegedit()
{
    QCoreApplication::setOrganizationName(QString("Bruce"));
    QCoreApplication::setApplicationName(QString("Test"));
    QSettings settings(QSettings::NativeFormat, QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName());
    QString strUUID = QUuid::createUuid().toString().remove("{").remove("}").remove("-");
    settings.setValue("key",strUUID);
    return strUUID;
}
bool AppKey::start()
{

    //从注册表中获取key的value
    QString strRegedit = ReadRegedit();
    if(strRegedit=="")
    {
        QString str = WriteRegedit();
        str = "请将以下字符串发送给供应商换取密钥："+str;
        Dialog dlg(nullptr,str);
        dlg.exec();
        exit(0);
    }
    else
    {
        //判断密钥文件是否存在,不存在则从资源文件复制出来,同时需要设置文件写权限
        QString keyName = qApp->applicationDirPath() + "/key.db";
        QFile keyFile(keyName);
        if (!keyFile.exists() || keyFile.size() == 0) {
            QString str  = "密钥文件丢失！请将以下字符串发送给供应商换取密钥："+strRegedit;
            Dialog dlg(nullptr,str);
            dlg.exec();
            exit(0);
        }
        //读取密钥文件
        keyFile.open(QFile::ReadOnly);
        QString Data = keyFile.readLine();
        keyFile.close();
        keyData = getDecrypt(Data,strRegedit);
        QString strDate = keyData.left(10)+"Bruce";
        QString keyValue = getEncrypt(strDate,strRegedit);
        if(Data!=keyValue)
        {
            qDebug()<<keyValue;
            QString str  = "注册码无效！请将以下字符串发送给供应商换取密钥："+strRegedit;
            Dialog dlg(nullptr,str);
            dlg.exec();
            exit(0);
        }
        else
        {    //将从注册码文件中的密文解密,与当前时间比较是否到期
            keyDate = keyData.left(10);
            QString nowDate = QDate::currentDate().toString("yyyy-MM-dd");
            if (nowDate > keyDate) {
                QString str  = "注册码已到期！请将以下字符串发送给供应商换取密钥："+strRegedit;
                Dialog dlg(nullptr,str);
                dlg.exec();
                exit(0);
            }
        }
    }
    return true;
}

void AppKey::stop()
{
    timer->stop();
}

void AppKey::checkTime()
{
    //找出当前时间与首次启动时间比较
    QDateTime now = QDateTime::currentDateTime();
    if (startTime.secsTo(now) >= (keyRun * 60)) {
        QMessageBox::critical(0, "错误", "试运行时间已到,请联系供应商更新注册码!");
        exit(0);
    }
}

QString AppKey::getXorEncryptDecrypt(const QString &data, char key)
{
    //采用异或加密,也可以自行更改算法
    QByteArray buffer = data.toLatin1();
    int size = buffer.size();
    for (int i = 0; i < size; i++) {
        buffer[i] = buffer.at(i) ^ key;
    }

    return QLatin1String(buffer);
}

QString AppKey::getDecrypt(const QString &data, QString key)
{
    QAESEncryption encryption(QAESEncryption::AES_128, QAESEncryption::ECB, QAESEncryption::ZERO);
    QByteArray hashKey2 = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Md5);
    QByteArray decodedText = encryption.decode(QByteArray::fromBase64(data.toLatin1()), hashKey2);
    qDebug()<<"decodedText:"<<decodedText;
    qDebug()<<"decodedText.toBase64():"<<decodedText.toBase64();
    qDebug()<<"QString::fromLatin1(decodedText.toBase64()):"<<QString::fromLatin1(decodedText.toBase64());
    return decodedText;
}

QString AppKey::getEncrypt(const QString &data, QString key)
{
    QAESEncryption encryption(QAESEncryption::AES_128, QAESEncryption::ECB, QAESEncryption::ZERO);
    QByteArray hashKey = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Md5);
    QString str_encode=QString::fromLatin1(hashKey.toBase64());
    QByteArray encodedText = encryption.encode(data.toUtf8(), hashKey);
    QString str_encode_text=QString::fromLatin1(encodedText.toBase64());
    qDebug()<<"decodedText:"<<str_encode_text;
    qDebug()<<"str_encode_text.size():"<<str_encode_text.size();
    return str_encode_text;
}

bool AppKey::checkCount(int count)
{
    if (keyUseCount) {
        if (count >= keyCount) {
            QMessageBox::critical(0, "错误", "设备数量超过限制,请联系供应商更新注册码!");
            return false;
        }
    }

    return true;
}
